<template>
  <div class="kxz-scheduledTask">
    <el-form :inline="true" class="header">
      <el-form-item label="选择日期：">
        <el-date-picker v-model="selDate" type="date" placeholder="选择日期" @change="handleChangeDate">
        </el-date-picker>
      </el-form-item>
      <el-form-item class="header__right" v-if="cuUserType ===1 || cuUserType ===2">
        <el-button :class="operateType === 'add' ? 'active' : ''" @click="handleOpenAndChange('add')">增加任务计划
        </el-button>
        <el-button :class="operateType === 'edit' ? 'active' : ''" @click="handleOpenAndChange('edit')">修改任务计划
        </el-button>
      </el-form-item>
      <el-radio-group v-model="selType" v-if="power ===1" :class="$style.topSelType">
        <el-radio label="业务组" :class="$style.topRadio">业务组</el-radio>
        <el-radio label="答疑组" :class="$style.topRadio">答疑组</el-radio>
        <el-radio label="回访组" :class="$style.topRadio">回访组</el-radio>
      </el-radio-group>
      <div class='div2' v-if='power===1'><!--控制只有夏寒梦可以导入-->
              <el-upload
                class="upload-demo dadai-upload"
                action="https://jsonplaceholder.typicode.com/posts/"
                ref="uploadAvatar"
                accept="*"
                :multiple="false"
                :auto-upload="false">
                <el-button size="small" type="primary">导入excel</el-button>
            </el-upload>
            <el-button size="small" type="primary"  class='sub' @click='submitUpload'>点击上传</el-button>
      </div>
    </el-form>
    <template v-if="cuUserType !== 3">
      <section class="container">
        <h2 class="sj-title">
          <i class="icon"></i>组任务</h2>
        <el-form class="task--all">
          <el-form-item label="呼出量：" class="task__item">
            <el-input v-model="cuTaskAll.hcl" readonly></el-input>
          </el-form-item>
          <el-form-item label="已完成：" class="task__item">
            <el-input v-model="cuTaskAll.finishHcl" readonly></el-input>
          </el-form-item>
          <el-form-item label="接听量：" class="task__item">
            <el-input v-model="cuTaskAll.jtl" readonly></el-input>
          </el-form-item>
          <el-form-item label="已完成：" class="task__item">
            <el-input v-model="cuTaskAll.finishJtl" readonly></el-input>
          </el-form-item>
          <el-form-item label="回访量：" class="task__item">
            <el-input v-model="cuTaskAll.hfl" readonly></el-input>
          </el-form-item>
          <el-form-item label="已完成：" class="task__item">
            <el-input v-model="cuTaskAll.finishHfl" readonly></el-input>
          </el-form-item>
        </el-form>
      </section>
    </template>
    <section class="container">
      <h2 :class="$style.posRel">
        <i class="icon"></i>组员任务
        <el-select v-model="grSelKfId" clearable placeholder="请选择客服" :class="$style.grSelKf">
          <el-option v-for="(item,index) in cuTaskGr" :key="index" :label="item.kfName" :value="item.id"></el-option>
        </el-select>
      </h2>
      <table>
        <tr>
          <th>客服名称</th>
          <th>呼出量</th>
          <th>已完成</th>
          <th>接听量</th>
          <th>已完成</th>
          <th>回访量</th>
          <th>已完成</th>
        </tr>
        <template v-if="cuGrList.length > 0">
          <tr v-for="(item,index) in cuGrList" :key="index">
            <td v-text="item.kfName"></td>
            <td v-text="item.hcl"></td>
            <td v-text="item.finishHcl"></td>
            <td v-text="item.jtl"></td>
            <td v-text="item.finishJtl"></td>
            <td v-text="item.hfl"></td>
            <td v-text="item.finishHfl"></td>
          </tr>
        </template>
        <template v-else>
          <tr>
            <td colspan="7">暂无记录</td>
          </tr>
        </template>
      </table>
    </section>
    <el-dialog :visible.sync="dialogFormVisible" :modal="false" class="dialog">
      <com-form>
        <el-form :model="dialogForm" label-width="80px">
          <el-form-item label="选择日期">
            <el-date-picker v-model="dialogForm.selDate" type="date" placeholder="请选择日期" :picker-options="pickerOptions0">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="任务类型">
            <el-select v-model="dialogForm.selTask" placeholder="请选择类型" @change="handleDialogTaskType">
              <el-option label="组员任务" value="0"></el-option>
              <el-option label="整组任务" value="1"></el-option>
            </el-select>
          </el-form-item>
          <template v-if="dialogForm.selTask !== '1'">
            <el-form-item label="选择客服">
              <el-select v-model="dialogForm.selKf" placeholder="请选择客服">
                <el-option v-for="(item,index) in kfList" :key="index" :label="item.UserName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </template>
          <div class="quantity">
            <el-form-item label="呼出量">
              <el-input v-model="dialogForm.callout"></el-input>
            </el-form-item>
            <el-form-item label="接听量">
              <el-input v-model="dialogForm.callin"></el-input>
            </el-form-item>
            <el-form-item label="回访量">
              <el-input v-model="dialogForm.revisit"></el-input>
            </el-form-item>
          </div>
        </el-form>
      </com-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmitTask">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ComForm from '../../../../components/comForm'
import { utils } from '../../../../config/mixin'
import {dateFormat} from 'vux'

export default {
  name: 'scheduled-task',
  mixins: [utils],
  data() {
    const { power } = this.$store.getters.getUserInfo
    return {
      power,
      selType:'业务组',
      selDate: new Date(),
      dialogFormVisible: false,
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      operateType: '',
      dialogForm: {
        selDate: '',
        selTask: '',
        selKf: '',
        callout: '',
        callin: '',
        revisit: ''
      },
      task: {},
      kfList: [],
      grSelKfId: '',
    }
  },
  watch: {
    selType(){
      this.getTaskData()
    }
  },
  computed: {
    cuUserType() {
      const { power } = this.$store.getters.getUserInfo
      return power
    },
    cuTaskAll() {
      const task = this.task
      const initAll = {
        hcl: 0,
        hfl: 0,
        jtl: 0,
        finishHcl: 0,
        finishHfl: 0,
        finishJtl: 0,
      }
      const isEmptyObject = this._isEmptyObject
      if (task && !isEmptyObject(task) && task.all && !isEmptyObject(task.all)) {
        return task.all
      } else {
        return initAll
      }
    },
    cuTaskGr() {
      const cuUserType = this.cuUserType
      const task = this.task
      const initArr = []
      if (cuUserType !== 3) {
        const isEmptyObject = this._isEmptyObject
        if (task && !isEmptyObject(task) && task.gr && task.gr.length > 0) {
          return task.gr
        } else {
          return initArr
        }
      } else {
        if (task) {
          initArr.push(task)
          return initArr
        } else {
          return initArr
        }
      }
    },
    cuCurGroup() {
      return this.$store.getters.getCurGroup
    },
    
    cuGrList() {
      const grSelKfId = this.grSelKfId
      const grAllKf = this.cuTaskGr
      if(grSelKfId === ''){
        return grAllKf
      } else {
        let tmpa
        grAllKf.forEach((kf) => {
          console.log(kf.id === grSelKfId)
          if(kf.id === grSelKfId){
            tmpa = [kf]
            return
          }
        })
        return tmpa
      }
    }
  },
  components: {
    ComForm
  },
  mounted() {
    // 加载初始计划信息
    this.getTaskData()
  },
  methods: {
    async submitUpload() {
        try{
          const formData = new FormData()
          const files = this.$refs.uploadAvatar.uploadFiles
          // 添加提交参数
          if(files.length > 0){
            formData.append('userfile', files[0]['raw'])
          }
          
          const url = window.path + 'Plan/uploadLb.do'
          const res = await fetch(url,{
            method:'post',
            mode:'cors',
            body:formData
          })
          const data = await res.json()
          if(data.state === 0 && data.content){
            this.$message({
              type:'success',
              message:'提交成功',
            })
            this.$refs.uploadAvatar.clearFiles();
            return
          }
          this.$message({
            type: 'error',
            message:data.message,
          })
        }catch(e){
          console.warn('接口kfgl/uploadQn.do:',e.message)
          this.$warn('接口kfgl/uploadQn.do执行出错')
        }
    },
    handleOpenAndChange(oType) {
      this.dialogForm.selTask =''
      this.dialogFormVisible = true
      this.operateType = oType
    },
    handleChangeDate(val) {
      
      if (val) {
        this.getTaskData()
      }
    },
    handleDialogTaskType(val) {
      let arr = this.$store.getters.getKf
      console.log(arr)
      let yewuArr=[];
      let huifangArr=[];
      let dayiArr=[];
      arr.forEach(function(item){
          if(item.UserGroupId===104){
            yewuArr.push(item)
          }else if(item.UserGroupId===100){
            dayiArr.push(item)
          }else if(item.UserGroupId===112){
            huifangArr.push(item)
          }
          return yewuArr,dayiArr,huifangArr
      })
     
      if(this.selType === '答疑组'){
        this.kfList=dayiArr
      }
      if(this.selType === '业务组'){
        this.kfList=yewuArr
      }
      if(this.selType === '回访组'){
        this.kfList=huifangArr
      }
      // this.kfList = val === '0' ? this.cuCurGroup : []
      this.dialogForm.selKf = ''
    },
    handleSubmitTask() {
      const { selDate, selKf, selTask, callout, callin, revisit } = this.dialogForm
      const IsAssignGroupTask = this._IsAssignGroupTask()
      const selDateInDay = this.selDate
      if (selDate === '') {
        this.$warn('日期不能为空')
        return
      }
      if (selTask === '') {
        this.$warn('任务类型不能为空')
        return
      }
      if (selTask == '0' && selKf === '') {
        this.$warn('客服不能为空')
        return
      }
      if (callout === '' && callin === '' && revisit === '') {
        this.$warn('呼出，接听，回访至少有一个不能为空')
        return
      }
      this.getAddOrUpdateTask()
    },
    _IsAssignGroupTask(){
      const o = this.cuTaskAll
      let flag = false
      for(let key in o){
        if(key === 'hcl' || key === 'jtl' || key === 'hfl'){
          if(o[key] !== 0){
            flag = true
          }
        }
      }
      return flag
    },
    _gCN2gId(cn){
      const groups = this.$store.getters.getGroup
     
      let selGroupId
      Object.entries(groups).forEach(item => {
        if(item[1] === cn){
          selGroupId = item[0]
        }
      })
      return selGroupId
    },
    async getTaskData() {
      try {
        const { sessionId , userGroupId , userGroup, power} = this.$store.getters.getUserInfo
        const date = this._dateFormat(this.selDate, 'yyyy-MM-dd')
        const selType = this.selType
        let groupId
        if(power === 1){
          groupId = this._gCN2gId(selType)
        }else{
          groupId = userGroupId
        }
        
        const { data } = await this.$get(this, {
          api: 'Plan/loadPlan.do',
          data: {
            sessionId,
            groupId,
            date
          }
        })
       
        if (data.state === 0) {
          this.grSelKfId = ''
          this.task = data.content
        }
        console.log(this.task)
      } catch (e) {
        this.$warn('系统Plan/loadPlan.do接口报错')
      }
    },
    async getAddOrUpdateTask() {
      const oType = this.operateType
      console.log(this.$store.getters.getKf)
      const api = oType === 'add' ? 'Plan/addPlan.do' : 'Plan/updatePlan.do'
      try {
        let userGroupId =this.$store.getters.getUserInfo.userGroupId
        const { selDate, selKf, callout, callin, revisit } = this.dialogForm
        const date = this._dateFormat(selDate, 'yyyy-MM-dd')
        if(this.selType==='业务组'){
          userGroupId =104
        }else if(this.selType==='答疑组'){
          userGroupId = 100
        }else if(this.selType==='回访组'){
          userGroupId = 112
        }
        const { data } = await this.$get(this, {
          api,
          data: {
            date,
            kfId: selKf,
            groupId:userGroupId,
            hcl: callout || 0,
            jtl: callin || 0,
            hfl: revisit || 0
          }
        })
        if (data.state === 0 && data.content === true) {
          this.$toast({
            message: `${oType === 'add' ? '添加' : '修改'}成功`
          })
          // 添加和修改成功之后更新数据列表
          await this.getTaskData()
          this.dialogFormVisible = false
        }else{
          this.$warn(data.message)
        }
      } catch (e) {
        this.$warn(`系统${api}接口报错`)
      }
    }
  }
}
</script>

<style lang="scss" module>
.topSelType{
  transform:translate(6px,5px);
  height:58px;
}
.topRadio {
  $tpListColor: #7b8897;
  color: $tpListColor;
  font-size: 18px !important;
}
.posRel{
  position:relative;
}

.grSelKf{
  position: absolute;
  right:0px;

}
</style>

<style lang="scss" scoped>
.header__right {
  margin-left: 100px;
}

.container {
  margin-bottom: 30px;
}

.el-button {
  $btnDftBgColor: #ecf0f3;
  $btnDftColor: #bac2cb;
  $btnChgBgColor: #5394fc;
  $btnChgColor: #fff;
  padding: 11px 29px;
  color: $btnDftColor;
  background: $btnDftBgColor;
  border: none;
  &:hover {
    color: $btnChgColor;
    background: $btnChgBgColor;
  }
  &.active {
    color: $btnChgColor;
    background: $btnChgBgColor;
  }
}

.task--all {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  width: 600px;
}

.task__item {
  width: 50%;
  text-align: left;
}

h2 {
  padding-bottom: 25px;
  font-size: 18px;
  color: #444;
}
.div2{
  margin-left:30px;
  width:300px;
  display: inline-block;
}
.div2 .upload-demo{
  float:left;
}
.div2 .sub{
  float:left;
  margin-left:15px;
}
table {
  $tableBorderColor: #dddfe6;
  $tableBgColor: #fff;
  width: 100%;
  border-top: 1px solid $tableBorderColor;
  border-left: 1px solid $tableBorderColor;
  th,
  td {
    border-right: 1px solid $tableBorderColor;
    border-bottom: 1px solid $tableBorderColor;
    background: $tableBgColor;
    text-align: center;
  }
  th {
    line-height: 50px;
  }
  td {
    line-height: 40px;
  }
}

.dialog {
  .el-date-editor {
    width: 100%;
  }
  .el-select {
    width: 100%;
  }
}

.quantity {
  .el-form-item {
    width: 80%;
    margin: 0 auto 20px auto;
  }
}

</style>

<style lang="scss">
.kxz-scheduledTask {
  .task__item {
    .el-form-item__content {
      display: inline-block;
    }
  }
  .dialog {
    .el-dialog {
      width: 400px;
    }
  }
  .quantity {
    margin-top: 35px;
    .el-form-item__label {
      font-size: 12px;
    }
    .el-input__inner {
      height: 30px;
    }
  }
  .el-dialog__footer {
    padding: 0 20px 25px;
    text-align: center;
  }
}
</style>
